<template>
    <div id="map">
        <div class="controldiv">
            <div @click="isShowRoutePanel=true"><img src="../assets/navi-icon.png"/></div>
            <div @click=""><img src="../assets/report_grey.png"/></div>
            <div @click="setStyleTest"> </div>
            <!--<div></div>-->
        </div>
        <div class="routePanel" v-if="isShowRoutePanel">
            <h3 style="display: inline">路径规划</h3>
            <i class="el-icon-close" style="float: right;font-size: 16px;" @click="isShowRoutePanel=false"></i>
            <el-form label-width="45px" :label-position="'left'" size="mini">
                <el-form-item label="起点:">
                    <el-input v-model="startPointStr" placeholder="请选择起点">
                        <el-button slot="append" icon="el-icon-coordinate" @click.prevent="getStartPoint"></el-button>
                    </el-input>
                </el-form-item>
                <el-form-item label="终点:">
                    <el-input v-model="endPointStr" placeholder="请选择终点">
                        <el-button slot="append" icon="el-icon-coordinate" @click="getEndPoint"></el-button>
                    </el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click.stop="routeAnalyze">路径规划</el-button>
                    <el-button type="primary" @click.stop="toNavigation">开始导航</el-button>
                </el-form-item>
            </el-form>

        </div>

        <div class="btn-list" v-show="false ">
            <button @click="initDrawCtrl">初始化绘制控件</button><br>
            <button @click="destoryDrawCtr">销毁绘制控件</button><br>
            <button @click="startDraw(0)">点</button>
            <button @click="startDraw(1)">圆</button>
            <button @click="startDraw(2)">线</button>
            <button @click="startDraw(3)">矩形</button>
            <button @click="startDraw(4)">多边形</button>
            <button @click="stopDraw">清除</button>
        </div>

    </div>

</template>

<script>
    import axios from 'axios'; // 引入axios
    import mapboxgl from "mapbox-gl";
    import "mapbox-gl/dist/mapbox-gl.css";
    import '../../public/js/leaflet/leaflet-mapbox-gl.js'
    import 'leaflet/dist/leaflet.css'
    import * as L from 'leaflet'
    import {basicMap, streetStyleMap, fiordStyleMap, nightStyleMap} from "../config/mapdata.js"

    // import 'leaflet.pm'
    // import 'leaflet.pm/dist/leaflet.pm.css'

    import 'leaflet-draw'
    import 'leaflet-draw/dist/leaflet.draw.css'

    export default {
        name: "Map",
        data() {
            return {
                roadNetHost: "http://192.168.0.121:3000",
                map: this.$rootMap.map,
                myIcon: L.icon({
                    iconUrl: require('../assets/marker-icon.png'),
                    // iconSize: [26, 36],
                    iconAnchor: [12, 36],
                    popupAnchor: [-3, -76]
                }),
                startIcon: L.icon({
                    iconUrl: require('../assets/start.png'),
                    // iconSize: [26, 30],
                    iconAnchor: [12, 36],
                    popupAnchor: [-3, -76]
                }),
                endIcon: L.icon({
                    iconUrl: require('../assets/end.png'),
                    // iconSize: [2, 36],
                    iconAnchor: [12, 36],
                    popupAnchor: [-3, -76]
                }),
                isShowRoutePanel: false,
                startPointStr: "",
                startPoint: null,
                endPointStr: '',
                endPoint: null,
                linesLayer: null,
                // L.Control.Draw 控件对象
                drawControl: null,
                // 绘制对象
                drawObj: null,
            }
        },
        mounted() {
            // this.addDataToMap();
            this.initMap();
            // 初始化绘制控件
            // this.initDrawCtrl();
        },
        methods: {
            initMap() {
                this.map = L.map('map', {
                    center: [31.86705, 118.79619],
                    zoom: 15,
                    zoomControl: false,
                    attributionControl: false,
                    layers: [basicMap, streetStyleMap, fiordStyleMap, nightStyleMap]
                });

                let baseLayers = {
                    '基础地图': basicMap,
                    '道路地图': streetStyleMap,
                    'friod地图': fiordStyleMap,
                    '夜间地图': nightStyleMap

                }
                //添加图层控件
                let layerControl = L.control.layers(baseLayers).addTo(this.map);

                // this.addPMcontrols();

                this.drawControl = new L.Control.Draw({
                    position:'bottomleft',
                    draw:{
                        polyline:true,
                        polygon:true,
                        rectangle:true,
                        marker:true
                    }
                });




            },
            getStartPoint() {
                this.map.off('click');
                this.map.on('click', e => {
                    this.startPointStr = e.latlng.lat.toFixed(6) + "," + e.latlng.lng.toFixed(6);
                    if (this.startPoint) {
                        this.map.removeLayer(this.startPoint)
                    }
                    this.startPoint = L.marker([e.latlng.lat, e.latlng.lng], {
                        icon: this.startIcon
                    }).addTo(this.map);
                });
            },
            getEndPoint() {
                this.map.off('click');
                this.map.on('click', e => {
                    this.endPointStr = e.latlng.lat.toFixed(6) + "," + e.latlng.lng.toFixed(6);
                    if (this.endPoint) {
                        this.map.removeLayer(this.endPoint);
                    }
                    this.endPoint = L.marker([e.latlng.lat, e.latlng.lng], {
                        icon: this.endIcon
                    }).addTo(this.map);
                });
            },
            async routeAnalyze() {
                this.map.off('click');
                // debugger
                if (!this.startPoint) {
                    this.$message({
                        message: '请选择起点',
                        type: 'warning'
                    });
                    return;
                }
                if (!this.endPoint) {
                    this.$message({
                        message: '请选择终点',
                        type: 'warning'
                    });
                    return;
                }
                let featureObj = await this.getNavmes();
                this.linesLayer = L.geoJSON(featureObj.lineFeature, {
                    style: feature => {
                        return {
                            color: 'rgba(49,136,30,1)',
                            weight: 8
                        };
                    }
                }).addTo(this.map);
            },
            toNavigation() {
                if (this.linesLayer) {
                    this.$router.push('/navimap').catch(e => {
                        // console.log(e);
                    });
                } else {
                    this.$message({
                        message: '请进行路径规划',
                        type: 'warning'
                    });
                }
            },
            async getNavmes() {
                let navMesObj = {
                    lineFeature: null,
                    pointFeature: null
                }
                let data = {
                    "isUsingRoad": 1,
                    "isReturnGuide": 1,
                    "nodes": [{"latitude": this.startPoint._latlng.lat, "longitude": this.startPoint._latlng.lng}, {
                        "latitude": this.endPoint._latlng.lat,
                        "longitude": this.endPoint._latlng.lng
                    }]
                };
                let res = await axios.post('http://192.168.0.121:5080/bdgis/route', data);
                let result = res.data;
                if (result.data != null) {
                    let points = result.data.points;
                    let feature = {
                        type: 'Feature',
                        properties: {},
                        geometry: {
                            type: 'LineString',
                            coordinates: []//coordinates
                        }
                    };
                    let pointsSourceData = {
                        type: 'FeatureCollection',
                        features: []
                    }
                    for (let i = 0; i < points.length; i++) {
                        let pointFeature = {
                            type: 'Feature',
                            geometry: {
                                type: 'Point',
                                coordinates: []//coordinates
                            }
                        };
                        let tmpLat = points[i].latitude;
                        let tmpLon = points[i].longitude;
                        let tmpPoint = [tmpLon, tmpLat];
                        //线的geojson
                        feature.geometry.coordinates.push(tmpPoint);
                        //多个点的geojson
                        if (i > 1) {
                            pointFeature.geometry.coordinates = tmpPoint;
                            pointsSourceData.features.push(pointFeature);
                        }
                    }
                    navMesObj.lineFeature = feature;
                    navMesObj.pointFeature = pointsSourceData;

                    this.$store.commit('SETSTARTPOINT', this.startPoint);
                    this.$store.commit('SETENDPOINT', this.endPoint);
                    this.$store.commit('SETPOINTS', points);
                    this.$store.commit('SETGUIDES', result.data.guides);
                    this.$store.commit('SETLINEFEATURE', feature);
                    this.$store.commit('SETPOINTFEATURE', pointsSourceData);
                    console.log(points);

                    console.log( result.data.guides);
                }
                return navMesObj;

            },
            // 启动绘制
            startDraw(idx) {
                // 先取消
                if(this.drawObj) {
                    this.drawObj.disable();
                }
                switch (idx) {
                    case 0: {// 点
                        this.drawObj = new L.Draw.Marker(this.map, this.drawControl.options.draw.marker);
                        break;
                    }
                    case 1: {// 圆
                        this.drawObj = new L.Draw.Circle(this.map, this.drawControl.options.draw.circle);
                        break;
                    }
                    case 2: {// 线
                        this.drawObj = new L.Draw.Polyline(this.map, this.drawControl.options.draw.polyline);
                        break;
                    }
                    case 3: {// 矩形
                        this.drawObj = new L.Draw.Rectangle(this.map, this.drawControl.options.draw.rectangle);
                        break;
                    }
                    case 4: {// 多边形
                        this.drawObj = new L.Draw.Polygon(this.map, this.drawControl.options.draw.polygon);
                        break;
                    }
                }
                // 启动
                this.drawObj.enable();
            },
            //清除绘制
            stopDraw() {
                // 删除全部绘制的图层
                if(this.drawLayerGrounp) {
                    this.drawLayerGrounp.clearLayers();
                }
                // 取消绘制操作
                this.drawObj.disable();
            },
            // 交互绘制回调
            drawCreatedBack(e) {
                console.log('绘制完成', e);
                // 绘制的图形图层对象
                let drawLayer = e.layer;
                // 判断当前没有图层组，需先添加
                if(!this.drawLayerGrounp) {
                    //图层组
                    this.drawLayerGrounp = new L.FeatureGroup();
                    // 添加
                    this.map.addLayer(this.drawLayerGrounp);
                }
                // 添加到图层组
                this.drawLayerGrounp.addLayer(drawLayer);
            },
            // 初始化绘制控件
            initDrawCtrl() {
                //初始化绘制控件
                this.drawControl = new L.Control.Draw({
                    position: 'topleft',//控件位置 'topleft'(默认), 'topright', 'bottomleft' or 'bottomright'
                    draw: {
                        polyline: true,
                        polygon: true,
                        rectangle: true,
                        circle: true,
                        marker: true,
                    }
                }).addTo(this.map);// 要添加到 L.map 对象中
                // 添加绘制完监听事件
                this.map.on(L.Draw.Event.CREATED, this.drawCreatedBack);
            },
            // 销毁绘制控件
            destoryDrawCtr() {
                // L.Control.Draw 控件对象
                this.drawControl = null;
                // 绘制对象
                this.drawObj = null;
                // 删除全部绘制的图层
                if(this.drawLayerGrounp) {
                    this.drawLayerGrounp.clearLayers();
                }
                // 取消绘制完监听事件，避免在真正开发中，其它地方也监听了 CREATED 事件
                this.container.map.off(L.Draw.Event.CREATED, this.drawCreatedBack);
            },


            addPMcontrols(){
                // 添加绘制工具
                this.map.pm.setLang("zh");
                this.pmcontrol = this.map.pm.addControls({
                    position: "bottomleft",
                    drawPolygon: true, //绘制多边形
                    drawMarker: true, //绘制标记点
                    drawCircleMarker: false, //绘制圆形标记
                    drawPolyline: true, //绘制线条
                    drawRectangle: false, //绘制矩形
                    drawCircle: false, //绘制圆圈
                    editMode: true, //编辑多边形
                    dragMode: true, //拖动多边形
                    cutPolygon: false, //添加⼀个按钮以删除多边形⾥⾯的部分内容
                    removalMode: true, //清除多边形
                });
                // 全局设置绘制样式
                this.map.pm.setPathOptions({
                    color: "orange",
                    fillColor: "green",
                    fillOpacity: 0.4,
                });

                // 或者单独设置绘制样式
                var options = {
                    // 连接线标记之间的线
                    templineStyle: {
                        color: "red",
                    },
                    // 提⽰线从最后⼀个标记到⿏标光标的线
                    hintlineStyle: {
                        color: "red",
                        dashArray: [5, 5],
                    },
                    // 绘制完成的样式
                    pathOptions: {
                        color: "orange",
                        fillColor: "green",
                    },
                };

                // 激活绘制多边形功能-1、单独设置某个模式的样式
                this.map.pm.enableDraw("Polygon", options);

                // 启用绘制--多边形功能
                // this.map.pm.enableDraw("Polygon", {
                //     snappable: true, //启⽤捕捉到其他绘制图形的顶点
                //     snapDistance: 20, //顶点捕捉距离
                // });

                // 关闭绘制--注意也可以关闭其他模式的绘制功能
                this.map.pm.disableDraw("Polygon");

                // 绘制事件监听
                this.map.on("pm:drawstart", (e) => {
                    console.log(e, "绘制开始第一个点");
                });
                this.map.on("pm:drawend", (e) => {
                    console.log(e, "禁⽌绘制、绘制结束");
                });
                this.map.on("pm:create", (e) => {
                    console.log(e, "绘制完成时调⽤");
                    if (e.shape == "Circle") {
                        console.log(e.layer._latlng, e.layer._radius, "绘制坐标");
                    } else {
                        console.log(e.layer._latlngs[0], "绘制坐标");
                    }

                });

                this.map.on('pm:remove',e=>{
                    console.log('移除');
                })

                this.map.on("pm:globalremovalmodetoggled", (e) => {
                    console.log(e, "清除图层时调用");
                });
            },

        }
    }
</script>

<style scoped>
    h3, p {
        padding: 0;
        margin: 0;
    }

    #map {
        width: 100%;
        flex: 1;
        position: relative;
    }

    .controldiv {
        width: 45px;
        height: 100px;
        position: absolute;
        right: 11px;
        top: 65px;

        border-radius: 10px;
        z-index: 999;
    }

    .controldiv > div {
        width: 45px;
        height: 45px;
        /*border: 1px solid red;*/
        border-radius: 10px;
        background: white;
        margin-top: 5px;
    }
    .controldiv>div:nth-child(2){
        padding: 10px;
    }

    .controldiv img {
        height: 100%;
        width: 100%;
    }

    .routePanel {
        width: 300px;
        position: absolute;
        left: 50%;
        bottom: 10px;
        transform: translateX(-50%);
        /*border: 1px solid red;*/
        border-radius: 10px;
        z-index: 999;
        background-color: rgba(255, 255, 255, 0.8);
        padding: 10px;
    }
    .btn-list {
        z-index: 2000;
        position: absolute;
        top: 2px;
        left: 80px;
    }

</style>
<style>

</style>